var basePath = $("#basePath").val();
var userType = $("#userType").val();

$(document).ready(function () {
    initCssElement();
    menuCss("设备管理");
    queryDeviceList(0,10);
    initQueryTerm();
    InitBindEvents();
    $("#show-count").change(function(){
        queryDeviceList(0,$("#show-count").val());
    })
});

function initCssElement(){

    $("#queryForm select[name='hospitalId']").val(null);
    $("#queryForm select[name='hospitalId']").select2({
        language: 'zh-CN',
        placeholder: '医院',
        allowClear: true});
    $("#queryForm select[name='manufacturerId']").val(null);
    $("#queryForm select[name='manufacturerId']").select2({
        language: 'zh-CN',
        placeholder: '厂商',
        allowClear: true
    });

    $("#queryForm select[name='maintainerId']").val(null);
    $("#queryForm select[name='maintainerId']").select2({
        language: 'zh-CN',
        placeholder: '维修商',
        allowClear: true
    });

    $("#queryForm select[name='supplierId']").val(null);
    $("#queryForm select[name='supplierId']").select2({
        language: 'zh-CN',
        placeholder: '经销商',
        allowClear: true
    });


    $("#lastUpkeepDate,#installDate,#acceptanceDate,#purchaseDate,#manufactureDate,#enableTime").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        forceParse: true,
        format: 'yyyy-mm-dd',
        minView: 2,
        todayBtn: true
    });
}

//初始化绑定事件
function InitBindEvents(){
    $("#add").click(function (){
        initAddDeviceData(1);
        $("#add-modal").iziModal("open",this);
    });

    $("#search").click(function (){
        queryDeviceList(0,10);
    });

    $("#saveDevice").click(function (){
        saveDevice();
    });

    $("#edit").click(function(){
        initAddDeviceData(2);
    });

    $("#execlReport").click(function (){
        location.href = basePath+"/device/importDevice";
    });

    $("#upload").click(function (){
        uploadDevice();
    });
}

function initAddDeviceData(type){
    var deviceStatus = $("#add-update-from").find("[name='deviceStatus']");
    if($(deviceStatus).html() == ""){
        queryDeviceStatusList();
    }

    var deviceTypeId = $("#add-update-from").find("[name='deviceTypeId']");
    if($(deviceTypeId).html() == ""){
        showDeviceType();
    }

    var hospitalId = $("#add-update-from").find("[name='hospitalId']");
    if($(hospitalId).html() == ""){
        $(hospitalId).html($("#queryForm select[name='hospitalId']").html());
    }

    var manufacturerId = $("#add-update-from").find("[name='manufacturerId']");
    if($(manufacturerId).html() == ""){
        $(manufacturerId).html($("#queryForm select[name='manufacturerId']").html());
    }

    var maintainerId = $("#add-update-from").find("[name='maintainerId']");
    if($(maintainerId).html() == ""){
        $(maintainerId).html($("#queryForm select[name='maintainerId']").html());
    }

    var supplierId = $("#add-update-from").find("[name='supplierId']");
    if($(supplierId).html() == ""){
        $(supplierId).html($("#queryForm select[name='supplierId']").html());
    }



    $("#add-update-from").find("select").val(null);
    $("#add-update-from").find("select").select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true
    });

    if(type==2){
        editDeviceInit();
    }
}

function queryDeviceStatusList(){
    var url = basePath + "/base/queryItem"
    publicAjax(url,"POST",{type:"device_status"},function (data) {
        if(data.ret == 200){
                var html = "";
                $.each(data.data,function (index,item) {
                    html += "<option value='"+item.itemId+"'>"+item.item+"</option>";
                })
                $("#add-update-from").find("[name='deviceStatus']").html(html);
                $("#add-update-from").find("[name='deviceStatus']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    })
}



$("#add-modal").iziModal({
    title: "编辑设备",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1200,
    zindex: 1044,
    group: '',
    loop: false,
    history: false,
    restoreDefaultContent: false,
    autoOpen: false,
    bodyOverflow: false,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: true,
    onOpening: function () {
        validator();
    },
    onOpened: function () {
    },
    onClosing: function () {
        $('#add-update-from')[0].reset();
        $("#add-update-from").data('bootstrapValidator').destroy();
        $('#add-update-from').find("[name='deviceId']").val("");
    },
    onClosed: function () {

    }
});


function queryDeviceList(start,limit){
    var allName = $("#queryForm").find("[name='allName']").val();
    var hospitalId = $("#queryForm select[name='hospitalId']").val();
    var manufacturerId = $("#queryForm select[name='manufacturerId']").val();
    var json = {allName:allName,hospitalId:hospitalId,manufacturerId:manufacturerId,start:start,end: $("#show-count").val()};

    var url = basePath+"/device/queryDeviceList"
    publicAjax(url,"POST",json,function (data) {
        if(data.ret == 200){
            bindDeviceList(data.data.list);
            $("#total-count").text(data.data.count);
            //Pagination(data.data.count,limit,(start/limit+1));
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}


function bindDeviceList(obj){
    $("#device_table").html("");

    var str = "";
    if(obj == null || obj.length == 0){
        str = "<tr><td class='text-center text-muted' colspan='15'>暂无设备信息</td></tr>";
        $("#device_table").html(str);
        return;
    }
    $.each(obj,function (index,item) {
        str+="<tr><td class='text-center text-muted'>"+(index+1)+"</td>" +
            "<td class='text-center text-muted'><input type='checkbox' class='flat-green' name='one' value='"+item.deviceId+"'></td>" +
            "<td class='text-center text-muted'><button type='button' class='btn btn-primary btn-xs' onclick='queryDeviceInfo("+item.deviceId+")' data-original-title='详情'><i class='fa fa-file-text-o'></i></button></td>" +
            "<td class='text-muted'>"+(item.deviceName == null ? '' : item.deviceName)+"</td>" +
            "<td class='text-muted'>"+(item.deviceModel == null ? '' : item.deviceModel)+"</td>" +
            "<td class='text-muted'>"+(item.sn == null ? '' : item.sn)+"</td>" +
            "<td class='text-muted'>"+(item.manufacturerName == null ? '' : item.manufacturerName)+"</td>"+
            "<td class='text-muted'>"+(item.supplierName == null ? '' : item.supplierName)+"</td>";
            if(userType != 1101){
                str+= "<td class='text-muted'>"+(item.hospitalName == null ? '' : item.hospitalName)+"</td>";
            }
            str+= "<td class='text-muted'>"+(item.maintainerName == null ? '' : item.maintainerName)+"</td>" +
            "<td class='text-muted'>"+(item.upkeepCycle == null ? '' : item.upkeepCycle)+"</td>" +
            "<td class='text-muted'>"+(item.purchaseDate == null ? '' : item.purchaseDate)+"</td>" +
            "<td class='text-muted'>"+(item.installDate == null ? '' : item.installDate)+"</td>" +
            "<td class='text-muted'>"+(item.deviceStatusItem == null ? '' : item.deviceStatusItem)+"</td>" +
            "<td class='text-muted'>"+(item.responsiblePerson == null ? '' : item.responsiblePerson)+"</td>" +
            "</tr>";
    });
    $("#device_table").html(str);
    initDomCss();

}

function initDomCss(){
    $('input[type="checkbox"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $("input[name='one']").on('ifChecked', function(event){
        var current = $(this).parents("tr").index();
        $("[name='one']:checked").each(function(i){
            if($(this).parents("tr").index()!=current){
                $(this).iCheck('uncheck');
            }
        });
    });
}


function initQueryTerm(){
    var url = basePath+"/base/queryHosital";
    $("#queryForm select[name='hospitalId']").html("");
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.hospitalId+"'>"+item.hospitalName+"</option>";
            });

            $("#queryForm select[name='hospitalId']").html(html);
            $("#queryForm select[name='hospitalId']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    url = basePath + "/base/queryManufacturer";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.manufacturerId+"'>"+item.manufacturerName+"</option>";
            });
            $("#queryForm select[name='manufacturerId']").html(html);
            $("#queryForm select[name='manufacturerId']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    url = basePath + "/base/queryMaintainer";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.maintainerId+"'>"+item.maintainerName+"</option>";
            });
            $("#queryForm select[name='maintainerId']").html(html);
            $("#queryForm select[name='maintainerId']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    url = basePath + "/base/querySupplier";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.supplierId+"'>"+item.supplierName+"</option>";
            });
            $("#queryForm select[name='supplierId']").html(html);
            $("#queryForm select[name='supplierId']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}


function showDeviceType(){
    var url = basePath+"/base/queryDeviceType";
    publicAjax(url,"POST",{},function (data) {
        var html = "";
        $.each(data.data,function (index,item) {
            html+="<option value='"+item.deviceTypeId+"'>"+item.name+"</option>";
        });
        $("#add-update-from").find("[name='deviceTypeId']").html(html);
        $("#add-update-from").find("[name='deviceTypeId']").val(null);
    });
}


function showDeviceTypeSubList(object,fn) {
    if($(object).val() == null || $(object).val() == ""){
        $("#add-update-from").find("[name='deviceTypeSubId']").html("");
        return;
    }
    var url = basePath+"/base/queryDeviceTypeSub";
    publicAjax(url,"POST",{parentId:$(object).val()},function (data) {
        var html = "";
        $.each(data.data,function (index,item) {
            html+="<option value='"+item.deviceTypeSubId+"'>"+item.name+"</option>";
        });
        $("#add-update-from").find("[name='deviceTypeSubId']").html(html);
        $("#add-update-from").find("[name='deviceTypeSubId']").val(null);
        $("#add-update-from").find("[name='deviceTypeSubId']").select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true});
        fn();
    });

}

function validator(){
    $('#add-update-from').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            deviceName: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },price : {
                validators: {
                    regexp: {
                        regexp:  /^[0-9]\d*(\.\d{1,2})?$/,
                        message: '请输入正确的金额'
                    }
                }
            },quantity:{
                validators: {
                    regexp: {
                        regexp:  /^\+?[1-9]\d*$/,
                        message: '请输入大于0的正整数'
                    }
                }
            },upkeepCycle:{
                validators: {
                    regexp: {
                        regexp:  /^\+?[1-9]\d*$/,
                        message: '请输入大于0的正整数'
                    }
                }
            }
        }
    });
}

var bl = false;
function saveDevice() {
    $('#add-update-from').bootstrapValidator('validate');
    if($('#add-update-from').data('bootstrapValidator').isValid()){
        if(!bl){
            bl = true;
            var url = basePath+"/device/addOrUpdateDevice";
            var price = $("#add-update-from").find("[name='price']").val();
            $("#add-update-from").find("[name='price']").val(price*100);
            publicAjax(url,"POST",$("#add-update-from"),function (data) {
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    queryDeviceList(0,10);
                    $("#add-modal").iziModal("close", this);
                    bl=false;
                }else{
                    $("#add-update-from").find("[name='price']").val(price/100);
                    flavrShowByTime(data.msg,null,"danger",false);
                    bl=false;
                }
            })
        }
    }
}

function editDeviceInit(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个设备", null, "danger", false);
        return;
    }
    var json = {"deviceId":$("input[name='one']:checked").val()};
    var url = basePath+"/device/queryDeviceInfo";
    publicAjax(url,"POST",json,function (data) {
        if(data.ret == 200){
            editDeviceBindData(data.data);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    })
}

function editDeviceBindData(obj){

    $("#add-update-from").find("[name='deviceId']").val(obj.deviceId);
    $("#add-update-from").find("[name='deviceName']").val(obj.deviceName == null ? '' : obj.deviceName);
    $("#add-update-from").find("[name='deviceModel']").val(obj.deviceModel == null ? '' : obj.deviceModel);
    $("#add-update-from").find("[name='sn']").val(obj.sn == null ? '' : obj.sn);
    $("#add-update-from").find("[name='placeOrigin']").val(obj.placeOrigin == null ? '' : obj.placeOrigin);
    $("#add-update-from").find("[name='specifications']").val(obj.specifications == null ? '' : obj.specifications);
    $("#add-update-from").find("[name='attachment']").val(obj.attachment == null ? '' : obj.attachment);
    $("#add-update-from").find("[name='assetsNo']").val(obj.assetsNo == null ? '' : obj.assetsNo);
    $("#add-update-from").find("[name='price']").val(obj.price == null ? '' :obj.price/100);
    $("#add-update-from").find("[name='quantity']").val(obj.quantity == null ? '' : obj.quantity);

    $("#add-update-from").find("[name='upkeepCycle']").val(obj.upkeepCycle == null ? '' : obj.upkeepCycle);
    $("#add-update-from").find("[name='lastUpkeepDate']").val(obj.lastUpkeepDate == null ? '' : obj.lastUpkeepDate);
    $("#add-update-from").find("[name='department']").val(obj.department == null ? '' : obj.department);
    $("#add-update-from").find("[name='installDate']").val(obj.installDate == null ? '' : obj.installDate);
    $("#add-update-from").find("[name='acceptanceDate']").val(obj.acceptanceDate == null ? '' : obj.acceptanceDate);
    $("#add-update-from").find("[name='purchaseDate']").val(obj.purchaseDate == null ? '' : obj.purchaseDate);
    $("#add-update-from").find("[name='enableTime']").val(obj.enableTime == null ? '' : obj.enableTime);



    $("#add-update-from").find("[name='manufactureDate']").val(obj.manufactureDate == null ? '' : obj.manufactureDate);
    $("#add-update-from").find("[name='responsiblePerson']").val(obj.responsiblePerson == null ? '' : obj.responsiblePerson);
    $("#add-update-from").find("[name='remark']").val(obj.remark == null ? '' : obj.remark);

    var hosiptalId = $("#add-update-from").find("[name='hospitalId']");
    showText(hosiptalId,obj.hospitalId);

    var manufacturerId = $("#add-update-from").find("[name='manufacturerId']");
    showText(manufacturerId,obj.manufacturerId);

    var maintainerId = $("#add-update-from").find("[name='maintainerId']");
    showText(maintainerId,obj.maintainerId);

    var supplierId = $("#add-update-from").find("[name='supplierId']");
    showText(supplierId,obj.supplierId);

    var deviceStatus = $("#add-update-from").find("[name='deviceStatus']");
    showText(deviceStatus,obj.deviceStatus);

    var deviceTypeId = $("#add-update-from").find("[name='deviceTypeId']");
    showText(deviceTypeId,obj.deviceTypeId);


    if(obj.deviceTypeId != null){
        showDeviceTypeSubList(deviceTypeId,function () {
            var deviceTypeSubId = $("#add-update-from").find("[name='deviceTypeSubId']");
            showText(deviceTypeSubId,obj.deviceTypeSubId);
        });
    }

    $("#add-modal").iziModal("open",this);


}


function showText(obj,value) {
    $(obj).val(value);
    var text2 =$(obj).find("option:selected").text();
    $(obj).select2({language:'zh-CN', placeholder:text2, allowClear:true});
}


function queryDeviceInfo(id){
    location.href = basePath+"/device/info?id="+id;
}


function uploadDevice() {
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个设备", null, "danger", false);
        return;
    }
    var keyId = $("input[name='one']:checked").val();
    var keyType = 1401;
    var root = basePath;
    var fileType = "device_file_type";
    var json ={keyId:keyId,keyType:keyType,root:root,fileType:fileType,type:fileType};

    $("#deviceFileDiv").fileUpload(
        json
    )
}

//分页
function Pagination(total,limit,current){
    $('.M-box3').empty();
    $('.M-box3').pagination({
        totalData:total,
        showData:limit,//数据总数totalData和每页显示的条数showData必须同时配置，否则默认使用总页数pageCount;limit可选值 5 10 20 50
        //pageCount:50,
        current:current,
        jump:true,
        coping:true,
        homePage:'首页',
        endPage:'末页',
        prevContent:'上页',
        nextContent:'下页',
        callback:function(index){
          start = (index.getCurrent()-1)*limit;
          limit = index.getShowData();
          queryDeviceList(start,limit);
        }
  });
} 